package org.stone.project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.time.Duration;

@RequestMapping
@RestController
public class DemoController {
    @Autowired
    private WebClient webClient;

    @GetMapping("test1")
    public Mono<String> test1(){
        Mono<String> demo = webClient.get()
                .uri("http://www.baidu.com")
                .retrieve()
                .bodyToMono(String.class);
        System.out.println("okokokok");
        return demo;
    }

    @GetMapping("test2")
    public Mono<String> test2(){
        String name = Thread.currentThread().getName();
        System.out.println(name);
        return Mono.fromCallable(()->{
            String name2 = Thread.currentThread().getName();
            System.out.println(name2);
            Thread.sleep(1000);
            return "1231234";
        });
    }

    @GetMapping(value = "test3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> test3(){
        String name = Thread.currentThread().getName();
        System.out.println(name);
        Flux<String> i_am_run = Flux.just("1", "2", "3")
                .doOnNext(e -> {
                    System.out.println("i am run");
                })
                .map(e -> {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                    String sonName = Thread.currentThread().getName();
                    System.out.println(sonName);
                    return e;
                })
                .take(2);
        System.out.println("你好");
        return i_am_run;
    }

    @GetMapping("test4")
    public Mono<String> test4(){
        String name = Thread.currentThread().getName();
        System.out.println(name);

        Mono<String> res = Mono.just("1").map(e -> {
            String name2 = Thread.currentThread().getName();
            System.out.println(name2);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            return "1";
        });

        return res;
    }
}
